package com.now.printer.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.now.printer.R;
import com.now.printer.adapter.RecentlyFileListAdapter;
import com.now.printer.base.BaseActivity2;
import com.now.printer.base.BaseFragment2;
import com.now.printer.db.DocumentsTable;
import com.now.printer.db.RecentlyTable;
import com.now.printer.ui.activity.FilePreviewAndPrintActivity;
import com.now.printer.ui.activity.PinTuActivity;
import com.now.printer.ui.activity.StickyNoteActivity;
import com.now.printer.utils.DbUtils;
import com.now.printer.widget.NBToolBar;

import org.xutils.DbManager;
import org.xutils.common.util.LogUtil;
import org.xutils.db.Selector;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

public class RecentlyFileFragment extends BaseFragment2 {
    public static final String FRAGMENT_PAGE_TYPE = "FRAGMENT_PAGE_TYPE";
    private RecyclerView mRecyclerView;

    private RecentlyFileListAdapter recentlyFileListAdapter;

    private List<RecentlyTable> totalList = new ArrayList<>();

    private DbManager db;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int fragmentType = -1;
        if (getArguments() != null) {
            fragmentType = getArguments().getInt(FRAGMENT_PAGE_TYPE, -1);
        }
        try {
             db = x.getDb(DbUtils.daoConfig);
            List<RecentlyTable> recentlyTableList = db.selector(RecentlyTable.class).findAll();
            if (recentlyTableList == null)
            db.save(new RecentlyTable());

            if (fragmentType == 1) {
                totalList.addAll(initRecentlyList(db));
                LogUtil.i("recently 长度是：" + totalList.toString());
            } else if (fragmentType == 2) {
                totalList.addAll(initCollectList(db));
                LogUtil.i("collect 长度是：" + initCollectList(db).toString());
            }
        } catch (DbException e) {
            e.printStackTrace();
            LogUtil.e(" recently file fragment onCreate DbException is : " + e.getMessage());
        }
    }

    private List<RecentlyTable> initRecentlyList(DbManager db)  {
        List<RecentlyTable> recentlyTableList = null;
         try {
             List<RecentlyTable> tempList = db.selector(RecentlyTable.class).findAll();
             if (tempList == null){
                 return new ArrayList<>();
             }
            recentlyTableList = db.selector(RecentlyTable.class)
                    .where("path", "!=", "null")
                    .or("path", "!=", "")
                    .findAll();
        } catch (DbException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
        return recentlyTableList != null ? recentlyTableList : new ArrayList<>();
    }

    private List<RecentlyTable> initCollectList(DbManager db) {
        List<RecentlyTable> recentlyTableList = null;
        try {
            recentlyTableList = db.selector(RecentlyTable.class)
                    .where("isCollected", "=", "true")
                    .and("path", "!=", "null")
                    .findAll();
        } catch (DbException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
        return recentlyTableList != null ? recentlyTableList : new ArrayList<>();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_tab;
    }

    private TextView txtTempTips;
    @Override
    public void doBusiness(Context mContext, View convertView) {
        mRecyclerView = (RecyclerView) convertView.findViewById(R.id.id_stickynavlayout_innerscrollview);


        txtTempTips = (TextView) convertView.findViewById(R.id.txt_temp_tips);

        if (totalList != null && totalList.size() == 0){
            txtTempTips.setVisibility(View.VISIBLE);
        }else {
            txtTempTips.setVisibility(View.GONE);
        }
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(),
                LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(linearLayoutManager);

        recentlyFileListAdapter = new RecentlyFileListAdapter(getActivity(), totalList, R.layout.item_recently_result_list, getArguments().getInt(FRAGMENT_PAGE_TYPE, -1));
        mRecyclerView.setAdapter(recentlyFileListAdapter);
        recentlyFileListAdapter.setOnItemClickLitener(new RecentlyFileListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, String type) {
                LogUtil.i("按下的item name是 ： " + totalList.get(position).getName());
                LogUtil.i("按下的item path是 ： " + totalList.get(position).getPath());
                Intent intent = new Intent();
                intent.setClass(getActivity(), FilePreviewAndPrintActivity.class);
                intent.putExtra(FilePreviewAndPrintActivity.INTENT_KEY_FILE_URI, totalList.get(position).getPath());
                intent.putExtra(FilePreviewAndPrintActivity.INTENT_KEY_FILE_NAME, totalList.get(position).getName());
                intent.putExtra(FilePreviewAndPrintActivity.INTENT_KEY_FILE_IMAGE, totalList.get(position).getImageId());
                intent.putExtra(FilePreviewAndPrintActivity.INTENT_KEY_FILE_LAST_TIME, totalList.get(position).getLastTime());
                intent.putExtra(FilePreviewAndPrintActivity.INTENT_KEY_FILE_SIZE, totalList.get(position).getSize());
                startActivity(intent);
            }

            @Override
            public void onItemClickCollect(int position, boolean isCollect) {
                LogUtil.i("点击收藏后： " + isCollect);
                x.task().run(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            DbManager db = x.getDb(DbUtils.daoConfig);
                            Selector<RecentlyTable> recentlyTableSelector = db.selector(RecentlyTable.class)
                                    .where("path", "=", totalList.get(position).getPath());
                            if (recentlyTableSelector.count() > 0 || recentlyTableSelector.findAll().size() > 0
                                    || recentlyTableSelector.getLimit() > 0) {

                                totalList.get(position).setIsCollected(String.valueOf(isCollect));

//                                parent.name = "hahaha123" + System.currentTimeMillis();
//                                parent.setEmail("wyouflf@gmail.com");
//                                db.update(parent);
//                                db.update(parent, "name", "email");
//                                db.update(Parent.class,
//                                        WhereBuilder.b("id", "=", 1).and("isAdmin", "=", true),
//                                        new KeyValue("name", "test_name"), new KeyValue("isAdmin", false));

                                db.update(totalList.get(position), "isCollected");

                                totalList.clear();
                                totalList.addAll(initRecentlyList(db));
                                LogUtil.i("查询到的最近文档是否存在getLimit ：" + recentlyTableSelector.getLimit());
                                LogUtil.i("查询到的最近文档是否存在findAll ：" + recentlyTableSelector.findAll());
                                LogUtil.i("查询到的最近文档是否存在 count ：" + recentlyTableSelector.count());
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        recentlyFileListAdapter.notifyDataSetChanged();

                                    }
                                });
                            } else {
                                LogUtil.i("最近列表没有这个文件， 因此无法收藏");
                            }
                        } catch (DbException e) {
                            e.printStackTrace();
                            LogUtil.i("saveCurrentFileToDatabase DbException：" + e.getMessage());
                        }
                    }
                });
            }
        });


    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            //隐藏
            LogUtil.i("当前隐藏");
        } else {
            //显示
            LogUtil.i("当前显示");
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (db != null){
            int fragmentType = getArguments().getInt(FRAGMENT_PAGE_TYPE, -1);
            if (fragmentType== 2 && isVisibleToUser) {
                LogUtil.i("setUserVisibleHint，当前收藏页");
                totalList.clear();
                totalList.addAll(initCollectList(db));
                recentlyFileListAdapter.notifyDataSetChanged();
            }else if (fragmentType == 1 && isVisibleToUser){
                LogUtil.i("setUserVisibleHint，当前最近记录页");
                totalList.clear();
                totalList.addAll(initRecentlyList(db));
                recentlyFileListAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    protected void onLazy() {

    }

    //type 1代表最近全部  type 2代表加入收藏的
    public static RecentlyFileFragment newInstance(int type) {
        RecentlyFileFragment tabFragment = new RecentlyFileFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(FRAGMENT_PAGE_TYPE, type);
        tabFragment.setArguments(bundle);
        return tabFragment;
    }


    @Override
    protected boolean isShowToolbar() {
        return false;
    }
}
